create or replace package pk_bitfinex is

  -- Author  : RELAXIMUS
  -- Created : 06.12.2013 23:03:19
  -- Purpose : bitfinex market adopter
  -- book retriever
  g_api_secret varchar2(100) := 'DLrmpUffBrhrV8GkQvAfc0CHHSxdae5sXChGa2Oq7NY';
  g_api_key    varchar2(100) := 'YJqMoJxX8w8oldCPBOgWjARNCKHE9LVr0XH0doTaas7';
  
  function book(a_code_from varchar2, a_code_to varchar2) return pk_tool.TBookStrArr pipelined;

end pk_bitfinex;
/
create or replace package body pk_bitfinex is
  g_last_call date;
  
  procedure check_freq 
  is
     l_cur_time date :=sysdate;
     l_limit    number;
  begin
    if g_last_call is null then 
       g_last_call := sysdate;
       return; 
    end if;
    select nvl(call_limit*1/24/60/60,0) into l_limit from t_market m where m.name = 'bitfinex';
    while l_cur_time-g_last_call<l_limit loop
      l_cur_time :=sysdate;
    end loop;
    g_last_call := sysdate;
  exception 
    when no_data_found then
      -- there is no such market or limit, well... never mind.
      g_last_call := sysdate;
  end;
  
  function book(a_code_from varchar2, a_code_to varchar2) return pk_tool.TBookStrArr pipelined
  is
       ret      json;
       jbs      json_list;
       j        json;
       str      pk_tool.TBookStr;
  begin
    check_freq ;
    -- if this is pair ltc - btc
    if a_code_to = 'ltc' and a_code_from = 'btc' then
        ret := json(pk_http.request('https://api.bitfinex.com/v1/book/ltcbtc'));
       -- buys
       jbs := json_list(ret.get('bids'));
       if jbs.count > 0 then
         for i in 1..jbs.count loop
           j := json(jbs.get(i));
           str.buysell:='buy';
           str.rate:=j.get('price').get_string;
           str.amount:=j.get('amount').get_string;
              pipe row (str);
         end loop;
       end if;
        -- sells
       jbs := json_list(ret.get('asks'));
       if jbs.count > 0 then
         for i in 1..jbs.count loop
           j := json(jbs.get(i));
           str.buysell:='sell';
           str.rate:=j.get('price').get_string;
           str.amount:=j.get('amount').get_string;
              pipe row (str);
         end loop;
       end if;
    end if;
    return;
  end;
end pk_bitfinex;
/
